<?php

namespace MoChat\ClientNew\Action;

use Carbon\Carbon;
use Hyperf\DbConnection\Db;
use MoChat\App\Sales\Model\SalesClientTaskEmployee;
use MoChat\App\Sales\Model\SalesTaskEmployee;
use MoChat\ClientNew\Model\ClientFollowRecord;
use MoChat\ClientNew\Model\ClientNew;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Qbhy\HyperfAuth\AuthManager;

/**
 * @Controller
 */
class Sale extends AbstractAction
{
    use ValidateSceneTrait;

    protected $auth;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/client-new/sale", methods="post")
     */
    public function handle(): array
    {
        $data = $this->request->all();
        $user =user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        $where = [];
        if (!$user['isRoot']) {
            $where[] = ['work_employee_id', '=', $user['workEmployeeId']];
        }
        if (!empty($data['start_time'])) {
            $where[] = ['start_time', '>=', $data['start_time']];
            $where[] = ['end_time', '<', $data['end_time']];
        }

        if (!empty($data['is_failure'])&&is_numeric($data['is_failure'])) {
            $nowTime = date('Y-m-d H:i:s');
            if ($data['is_failure'] == 1) {
                $where[] = ['end_time', '>', $nowTime];
            } else {
                $where[] = ['end_time', '<', $nowTime];
            }
        }
//        dd($where);
        $option = ['orderByRaw' => 'id desc', 'perPage' => 10, 'page' => $data['page'], 'pageName' => 'page'];
        $results=(new SalesTaskEmployee())->getPageList($where,['*'],$option);
        foreach ($results['data'] as &$v){
            $clientIds=ClientNew::query()->where('work_employee_id',$v['workEmployeeId'])->where('unique_id','>',0)->pluck('unique_id')->toarray();
           $user_ids=Db::connection('b2b')->table('user')->whereIn('unique_id',$clientIds)->pluck('id')->toArray();
            $sales_task_yes=Db::connection('b2b')->table('user_order')
                ->join('order_status as status', 'status.ID', 'user_order.ID')
                ->where('status.PAYMENT', 1)
                ->where('user_order.CREATE_TIME', '>=', $v['startTime'])
                ->where('user_order.CREATE_TIME', '<', $v['endTime'])
                ->whereIn('user_order.user_id',$user_ids)
                ->sum(Db::raw("my_user_order.TOTAL_AMOUNT + my_user_order.FREIGHT_AMOUNT"));
            $sales_task_no=0;
            if ($sales_task_yes<$v['salesTask']){
                $sales_task_no=round(($v['salesTask']-$sales_task_yes),2);
            }
            $v['failure'] = '未失效';
            if (strtotime($v['endTime']) < time()) {
                $v['failure'] = '已失效';
            }
            $v['sales_task_no']=$sales_task_no;
            $v['sales_task_yes']=$sales_task_yes;
        }
        return $results;
    }
    public function checkLicence($licence_date){
        if ($licence_date<Carbon::now()->toDateTimeString()){
            return false;
        }
        return true;
    }
}
